<template>
	<view class="page group-add">
		<nav-header title="发起群聊" :show-right="false">
			<!-- <template v-slot:right>
				<view class="confirm-text" @click="initGroup">创建</view>
			</template> -->
		</nav-header>

		<!-- <view class="notice">
			<up-notice-bar :text="text" icon="info-circle"></up-notice-bar>
		</view> -->


		<view style="width: 100%;">
			<view class="search">
				<up-search placeholder="搜索通讯录" v-model="searchText" :clearabled="true" :showAction="false"
					bg-color="#ffffff" search-icon-color="#474a52" placeholder-color="#82868d" height="40"></up-search>
			</view>
		</view>


		<!-- 		<view class="checked">
			<text>已选：{{ selectedCount }}/500</text>
		</view> -->


		<view class="member-items">
			<up-index-list :index-list="friendIdx" v-if="friendGroups.length>0">
				<template v-for="(friends, i) in friendGroups">
					<up-index-item>
						<up-index-anchor :text="friendIdx[i] == '*' ? '在线' : friendIdx[i]"
							bgColor="#f2f3fd"></up-index-anchor>
						<view v-for="friend in friends" v-show="!searchText || friend.nickName.includes(searchText)"
							:key="friend.id">
							<view class="member-item" @click="onSwitchChecked(friend)">
								<view class="friend-checked">
									<checkbox-group>
										<checkbox :checked="friend.checked" :disabled="friend.disabled" color="#1989FA"
											@tap.stop.native="onSwitchChecked(friend)" />
									</checkbox-group>
								</view>
								<head-image :name="friend.nickName" :online="friend.online" :url="friend.headImage"
									:size="90"></head-image>

								<view class="member-name">{{ friend.nickName }}</view>
							</view>
						</view>
					</up-index-item>
				</template>
			</up-index-list>
			<view v-else>
				<up-empty mode="data" text="暂无好友">
				</up-empty>
			</view>
		</view>

		<up-loading-page :loading="loading"></up-loading-page>

		<view class="tabbar">
			<view class="list">
				<view class="left">
					<text class="text-sm-Regular" style="color: #A4A7AE;">已选择：</text><text class="text-sm-Medium"><text
							style="color: #2970FF;">{{inviteSize}}</text>/{{friendItems.length}}人</text>
				</view>
				<view class="right">
					<button class="btncolor" type="primary" size="mini" @tap.once="initGroup()">
						<text class="text-md-Medium">确认邀请</text>
					</button>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		pinyin
	} from 'pinyin-pro';
	export default {
		data() {
			return {
				text: "若您要发起友商群，请在发起群聊后在群：聊天页面-右上角-升级为友商群",
				groupType: null,
				searchText: "",
				groupMembers: [],
				friendItems: [],
				selectedItems: [],
				selectedCount: 0,
				loading: false //加载
			}
		},
		methods: {
			initGroup() {
				this.loading = true
				let ids = this.selectedItems.map(item => item.id)
				const result = {
					ids: ids,
					groupType: this.groupType
				};
				this.$http({
					url: "/group/createGroupByFriendIds",
					method: 'POST',
					data: result
				}).then((group) => {
					this.groupStore.addGroup(group);
					uni.showToast({
						title: "邀请成功",
						icon: 'none'
					})
					this.loading = false
					setTimeout(() => {
						// 等待后跳转
						uni.redirectTo({
							url: `/pageSubOne/chat/chat-box?id=${group.id}&type=GROUP&sourceType=${this.groupType}`
						})
					}, 1000);

				})
			},
			onShowUserInfo(userId) {
				uni.navigateTo({
					url: "/pageSubOne/common/user-info?id=" + userId
				})
			},
			onSwitchChecked(friend) {
				if (!friend.disabled) {
					friend.checked = !friend.checked;
					if (friend.checked) {
						this.selectedItems.push(friend)
						this.selectedCount++;
					} else {
						const index = this.selectedItems.findIndex(item => item.id === friend.id)
						if (index !== -1) {
							this.selectedItems.splice(index, 1)
						}
						this.selectedCount--;
					}
				}
			},
			initFriendItems() {
				this.friendItems = [];
				let friends = []
				if (this.groupType == 0) {
					friends = this.groupMembers.filter(item => item.friendType == 0);
				} else if (this.groupType == 1) {
					friends = this.groupMembers.filter(item => item.friendType == 1);
				}
				// let friends = this.friendStore.friends;
				// console.log(this.friendStore.friends)
				friends.forEach((f => {
					let item = {
						id: f.id,
						headImage: f.headImage,
						nickName: f.nickName,
						online: f.online
					}
					// item.disabled = this.isGroupMember(f.id);
					item.checked = false
					this.friendItems.push(item);
				}))
			},
			loadGroupMembers() {
				this.$http({
					url: `/friend/list`,
					method: "GET"
				}).then((members) => {
					this.groupMembers = members.filter(m => !m.quit);
					this.initFriendItems();
				})
			},

			isGroupMember(id) {
				return this.groupMembers.some(m => m.userId == id);
			},

			firstLetter(strText) {
				// 使用pinyin-pro库将中文转换为拼音
				let pinyinOptions = {
					toneType: 'none', // 无声调
					type: 'normal' // 普通拼音
				};
				let pyText = pinyin(strText, pinyinOptions);
				return pyText[0];
			},
			isEnglish(character) {
				return /^[A-Za-z]+$/.test(character);
			}
		},
		computed: {
			inviteSize() {
				return this.friendItems.filter(f => !f.disabled && f.checked).length;
			},
			friendGroupMap() {
				// 按首字母分组
				let groupMap = new Map();
				this.friendItems.forEach((f) => {
					if (this.searchText && !f.nickName.includes(this.searchText)) {
						return;
					}
					let letter = this.firstLetter(f.nickName).toUpperCase();
					// 非英文一律为#组
					if (!this.isEnglish(letter)) {
						letter = "#"
					}
					if (f.online) {
						letter = '*'
					}
					if (groupMap.has(letter)) {
						groupMap.get(letter).push(f);
					} else {
						groupMap.set(letter, [f]);
					}
				})
				// 排序
				let arrayObj = Array.from(groupMap);
				arrayObj.sort((a, b) => {
					// #组在最后面
					if (a[0] == '#' || b[0] == '#') {
						return b[0].localeCompare(a[0])
					}
					return a[0].localeCompare(b[0])
				})
				groupMap = new Map(arrayObj.map(i => [i[0], i[1]]));
				return groupMap;
			},
			friendIdx() {
				return Array.from(this.friendGroupMap.keys());
			},
			friendGroups() {
				return Array.from(this.friendGroupMap.values());
			}
		},
		onLoad(options) {
			this.groupType = options.groupType;
			this.loadGroupMembers();
		}
	}
</script>

<style lang="scss" scoped>
	.group-add {
		position: relative;
		border: #dddddd solid 1px;
		display: flex;
		flex-direction: column;

		.confirm-text {
			font-size: 30rpx;
			color: #1989FA;
		}

		.notice {
			padding: 0 30rpx;
		}

		.search {
			padding-bottom: 20rpx;
			height: 90rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			// width: 100%;
			// margin: 0 auto;
			padding: 10rpx 32rpx;

			:deep(.u-search__content) {
				border-radius: 30px !important;
				height: 72rpx;
			}

			:deep(.u-search) {
				border-radius: 30px !important;
				border: 1rpx solid $gray-200;
			}
		}

		.checked {
			color: #aaa;
			padding: 10rpx 30rpx;
			font-size: 30rpx;
		}

		.member-items {
			position: relative;
			flex: 1;
			// overflow: hidden;
			padding-bottom: 174rpx;

			.member-item {
				height: 120rpx;
				display: flex;
				margin-bottom: 1rpx;
				position: relative;
				padding: 0 30rpx;
				align-items: center;
				background-color: white;
				white-space: nowrap;

				.friend-checked {
					margin-right: 20rpx;
				}

				.member-name {
					flex: 1;
					padding-left: 20rpx;
					font-size: 30rpx;
					font-weight: 600;
					line-height: 60rpx;
					white-space: nowrap;
					overflow: hidden;
				}
			}

			.scroll-bar {
				height: 100%;
			}
		}

		.tabbar {
			width: 100%;
			position: fixed;
			bottom: 0;
			left: 0;
			padding-bottom: 42rpx;
			border-top: 1rpx solid $gray-200;
			background-color: $white;
			z-index: 100;

			.list {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 24rpx 32rpx;

				.left {
					color: $gray-900;
				}

				.right {
					.btncolor {
						background-color: $brand-500;
						color: $white;
						padding: 16rpx 32rpx;
						border-radius: 40rpx;
						text-align: center;
						line-height: 46rpx;
						vertical-align: middle;
					}
				}
			}
		}
	}
</style>